package com.spark.data

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.CheckBox
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.spark.colliery.common.ext.gone
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.report
import com.spark.common.ext.wrapIO
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.data.model.CrewListModel
import kotlinx.android.synthetic.main.frag_select_crew.*
import org.jetbrains.anko.sdk25.coroutines.onCheckedChange

/**
 * select the crew to transfert somebody
 */
class CrewsFragment : BaseFragment() {
    private lateinit var crewAdapter: CrewAdapter

    companion object {
        val res_crew = 0x112
        fun newInstance(): CrewsFragment {
            val fragment = CrewsFragment()
            val args = Bundle()

            fragment.arguments = args
            return fragment
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_select_crew
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        iv_back.setOnClickListener { pop() }

        crewAdapter = CrewAdapter(R.layout.item_crew)
        recy_crew.adapter = crewAdapter
        recy_crew.layoutManager = LinearLayoutManager(context)
        crewAdapter.addData(mutableListOf(
                CrewListModel.ResultMap(),
                CrewListModel.ResultMap(),
                CrewListModel.ResultMap(),
                CrewListModel.ResultMap(),
                CrewListModel.ResultMap(),
                CrewListModel.ResultMap(),
                CrewListModel.ResultMap()
        ))

        crewAdapter.setOnItemClickListener { adapter, view, position ->
            val data = crewAdapter.data[position]
            data.isSelected = !data.isSelected
            crewAdapter.notifyItemChanged(position)
        }

        crewAdapter.addOnCountChangeListener {
            val selectSize = crewAdapter.results.size
            LogUtils.e(selectSize)
            rl_select_summary.gone(selectSize == 0)
            tv_selected_count.text = "$selectSize"
        }

        tv_search.setOnClickListener {
            hideSoftInput()
            val keyword = et_search.text.toString().trim()
            /**
             * 通过将string转为Integer来判断该字符串是否为数字
             */
            try {
                val numKey = Integer.valueOf(keyword)
                fetchCrews(destNo = keyword)
            } catch (e: Throwable) {
                fetchCrews(destUser = keyword)
            }
        }

        btn_sure.setOnClickListener {
            val results = crewAdapter.results
            val bundle = Bundle()
            bundle.putString("crew", Gson().toJson(results))
            setFragmentResult(res_crew, bundle)
            pop()
        }
    }

    override fun onLazyInitView(savedInstanceState: Bundle?) {
        super.onLazyInitView(savedInstanceState)
        fetchCrews()
    }

    /**
     * @destUser 姓名
     * @destNo 工号
     */
    @SuppressLint("CheckResult")
    private fun fetchCrews(destUser: String = "", destNo: String = "") {
        val params = mutableMapOf(
                Pair(Const.qr_transferUser, destUser),
                Pair(Const.qr_transferemplyeeno, destNo)
        )
        Http.request()
                .rxPost("${Const.base_url}${Const.act_trans_crew_list}", if (destNo.isNullOrBlank() && destUser.isNullOrBlank()) "{}".toJsonBody() else params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            LogUtils.e(it)
                            Gson().fromJson(it, CrewListModel::class.java)?.apply {
                                if (code == "200") {
                                    crewAdapter.data.clear()
                                    crewAdapter.results.clear()
                                    crewAdapter.addData(resultMaps)
                                } else {
                                    error(msg)
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                        },
                        {},
                        {
                            dispose = it
                        }
                )
    }

}

class CrewAdapter(layoutRes: Int) : BaseQuickAdapter<CrewListModel.ResultMap, BaseViewHolder>(layoutRes) {
    val results: MutableList<CrewListModel.ResultMap> = mutableListOf()
    private var onCountChangeListener: OnCountChangeListener? = null

    override fun convert(helper: BaseViewHolder?, item: CrewListModel.ResultMap?) {
        if (item == null) return
        helper?.apply {
            //setText(R.id.tv_name, item.name)
            setText(R.id.tv_name, "张三")
            //setText(R.id.tv_no, item.employeeno)
            setText(R.id.tv_no, "12345678")
            //setText(R.id.tv_depart, item.departmentName)
            setText(R.id.tv_depart, "后勤管理处")
            val cbox = getView<CheckBox>(R.id.cb)
            cbox.isChecked = item.isSelected
            cbox.onCheckedChange { buttonView, isChecked ->
                item.isSelected = isChecked
                if (isChecked) {
                    if (!results.contains(item))
                        results.add(item)
                } else {
                    if (results.contains(item))
                        results.remove(item)
                }
                onCountChangeListener?.onChanged()
            }
        }
    }

    fun addOnCountChangeListener(listener: () -> Unit) {
        onCountChangeListener = object : OnCountChangeListener {
            override fun onChanged() {
                listener()
            }
        }
    }

    interface OnCountChangeListener {
        fun onChanged()
    }
}